// MyClass.cs
// 
// Copyright © 2009 FreeZzaph
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace LibFreeZzaph.FourChan
{
	
	public class FourChanPlugin : IFreeZzaphContentProviderPlugin 
	{
		private static readonly Regex categoryRegex = new Regex(@"<a.+?href=""?(.+?/(\w+)/\w+\.html)""?.+?class=""boardlink""[^>]*?>([^<]+?)</a>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
		
		private IDictionary<string, CategoryGroup> categoryGroups;
		
		public string Name
		{
			get { return "4chan"; }
		}
		
		public string Title
		{
			get { return "4chan Image Boards"; }
		}
		
		public IDictionary<string, CategoryGroup> CategoryGroups
		{
			get
			{
				if (categoryGroups == null)
				{
					categoryGroups = new Dictionary<string, CategoryGroup>();
					
					Uri categoryUrl = new Uri("http://www.4chan.org/");
					
					string categoryData;
					try
					{
						categoryData = FreeZzaphUtility.FetchUrl(categoryUrl);
					}
					catch (Exception e)
					{
						throw new PluginException("Could not download category page. 4chan.org may not be accessible, or the plugin may need to be updated to reflect changes on the web site.", e);
					}
					
					IDictionary<string, Category> boardCategories = new Dictionary<string, Category>();
					
					Match matcher = categoryRegex.Match(categoryData);
					while (matcher.Success)
					{
						// Extract data from match
						string description = FreeZzaphUtility.DecodeHtmlEntities(matcher.Groups[3].ToString());
						string name = matcher.Groups[2].ToString();
						string url = matcher.Groups[1].ToString();
						
						// Create board categories
						FourChanBoardCategory fourChanBoardCategory = new FourChanBoardCategory(name, description, url);
						boardCategories.Add(fourChanBoardCategory.Name, fourChanBoardCategory);
												
						matcher = matcher.NextMatch();
					}
					
					// Create category groups
					CategoryGroup boards = new CategoryGroup("boards", "Image boards", boardCategories);
					
					categoryGroups.Add(boards.Type, boards);
				}
				
				return categoryGroups;
			}
		}
		
		public void Initialize(IPluginManager pm)
		{
		}
	}
}
